package com.ruoyi.system.service.impl;

import java.sql.Time;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageInfo;
import com.ruoyi.common.constant.ErrorCode;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.exception.ExceptionCast;
import com.ruoyi.system.domain.ImUser;
import com.ruoyi.system.domain.dto.ImUserGroupDeleteDto;
import com.ruoyi.system.domain.dto.ImUserGroupDto;
import com.ruoyi.system.domain.dto.ImUserGroupUpdateDto;
import com.ruoyi.system.domain.vo.ImUserGroupDetailVo;
import com.ruoyi.system.domain.vo.ImUserGroupListVo;
import com.ruoyi.system.domain.vo.ImUserGroupUserVo;
import com.ruoyi.system.im.TencentCloudImUtil;
import com.ruoyi.system.mapper.ImUserMapper;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.system.mapper.ImUserGroupMapper;
import com.ruoyi.system.domain.ImUserGroup;
import com.ruoyi.system.service.IImUserGroupService;

import static com.ruoyi.common.utils.PageUtils.getDataTable;
import static com.ruoyi.common.utils.PageUtils.startPage;

/**
 * 群组Service业务层处理
 * 
 * @author ruoyi
 * @date 2024-04-02
 */
@Service
public class ImUserGroupServiceImpl extends ServiceImpl<ImUserGroupMapper, ImUserGroup> implements IImUserGroupService
{
    @Autowired
    private ImUserGroupMapper imUserGroupMapper;

    @Autowired
    private ImUserMapper imUserMapper;

    @Autowired
    private TencentCloudImUtil tencentCloudImUtil;


    @Override
    public void addGroup(ImUserGroupDto groupDto) {
        List<String> userIDList=groupDto.getUserIds().stream().map(x->{
            ImUser imUser = imUserMapper.selectById(x);
            return imUser.getUserId();
        }).collect(Collectors.toList());

        ImUser owner = imUserMapper.selectById(groupDto.getOwnerId());

        String groupId = tencentCloudImUtil.addGroup(owner.getUserId(),groupDto.getGroupName(), userIDList);
        if (ObjectUtils.isNotEmpty(groupId)){
            ImUserGroup imUserGroup=new ImUserGroup();
            imUserGroup.setGroupName(groupDto.getGroupName());
            imUserGroup.setOwnerId(groupDto.getOwnerId());
            imUserGroup.setCreateTime(new Date());
            imUserGroup.setGroupId(groupId);
            imUserGroupMapper.insert(imUserGroup);
        }else {
            ExceptionCast.cast(ErrorCode.ADD_GROUP_FAIL);
        }
    }

    @Override
    public TableDataInfo groupList(String groupName) {
        startPage();
        LambdaQueryWrapper<ImUserGroup> userGroupLambdaQueryWrapper=new LambdaQueryWrapper<>();
        userGroupLambdaQueryWrapper.like(ObjectUtils.isNotEmpty(groupName),ImUserGroup::getGroupName,groupName);
        userGroupLambdaQueryWrapper.orderByDesc(ImUserGroup::getCreateTime);
        List<ImUserGroup> imUserGroups = imUserGroupMapper.selectList(userGroupLambdaQueryWrapper);
        long total = new PageInfo<>(imUserGroups).getTotal();
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        List<ImUserGroupListVo> listVos=imUserGroups.stream().map(x->{
            ImUserGroupListVo listVo=new ImUserGroupListVo();
            listVo.setId(x.getId());
            ImUser imUser = imUserMapper.selectById(x.getOwnerId());
            listVo.setOwnerId(imUser.getId());
            listVo.setOwnerUserId(imUser.getUserId());
            listVo.setOwnerNickName(imUser.getNickName());
            listVo.setGroupName(x.getGroupName());
            listVo.setCreateTime(sdf.format(x.getCreateTime()));
            listVo.setGroupId(x.getGroupId());
            return listVo;
        }).collect(Collectors.toList());
        return getDataTable(listVos,total);
    }

    @Override
    public ImUserGroupDetailVo groupDetail(Long id) {
        ImUserGroup imUserGroup = imUserGroupMapper.selectById(id);
        Map map = tencentCloudImUtil.groupDetail(imUserGroup.getGroupId());
        ImUserGroupDetailVo detailVo=new ImUserGroupDetailVo();
        detailVo.setId(id);
        detailVo.setGroupId(imUserGroup.getGroupId());
        detailVo.setName((String) map.get("Name"));
        detailVo.setIntroduction((String) map.get("Introduction"));
        return detailVo;
    }

    @Override
    public void updateGroup(ImUserGroupUpdateDto updateDto) {
        ImUserGroup imUserGroup = imUserGroupMapper.selectById(updateDto.getId());
        Boolean update = tencentCloudImUtil.update(imUserGroup.getGroupId(), updateDto.getName(), updateDto.getIntroduction());
        if (update){
            imUserGroup.setGroupName(updateDto.getName());
            imUserGroupMapper.updateById(imUserGroup);
        }else {
            ExceptionCast.cast(ErrorCode.UPDATE_GROUP_FAIL);
        }
    }

    @Override
    public TableDataInfo userList(Long groupId) {
        startPage();
        ImUserGroup imUserGroup = imUserGroupMapper.selectById(groupId);
        List<Map> maps = tencentCloudImUtil.groupUserList(imUserGroup.getGroupId());
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        long total = new PageInfo<>(maps).getTotal();
        List<ImUserGroupUserVo> userVos = maps.stream().map(x -> {
            String userId = (String) x.get("Member_Account");
            LambdaQueryWrapper<ImUser> imUserLambdaQueryWrapper = new LambdaQueryWrapper<>();
            imUserLambdaQueryWrapper.eq(ImUser::getUserId, userId);
            ImUser imUser = imUserMapper.selectOne(imUserLambdaQueryWrapper);
            ImUserGroupUserVo userVo = new ImUserGroupUserVo();
            userVo.setId(imUser.getId());
            userVo.setUserID(userId);
            userVo.setNickName(imUser.getNickName());
            //角色
            if ("Owner".equals(x.get("Role"))) {
                userVo.setRole("群主");
            } else if ("Admin".equals(x.get("Role"))) {
                userVo.setRole("群管理员");
            } else if ("Member".equals(x.get("Role"))) {
                userVo.setRole("群成员");
            }
            //进群时间
            Long time = (Integer) x.get("JoinTime") * 1000L;
            Time join = new Time(time);
            userVo.setJoinTime(sdf.format(join));
            return userVo;
        }).collect(Collectors.toList());
        return getDataTable(userVos,total);
    }

    @Override
    public void delete(Long id) {
        ImUserGroup imUserGroup = imUserGroupMapper.selectById(id);
        boolean b = tencentCloudImUtil.deleteGroup(imUserGroup.getGroupId());
        if (b){
            imUserGroupMapper.deleteById(imUserGroup);
        }else {
            ExceptionCast.cast(ErrorCode.DELETE_GROUP_FAIL);
        }
    }

    @Override
    public void deleteUser(ImUserGroupDeleteDto deleteDto) {
        ImUserGroup imUserGroup = imUserGroupMapper.selectById(deleteDto.getGroupId());
        //判断删除的是不是群主
        for (String groupUserId : deleteDto.getGroupUserIds()) {
            LambdaQueryWrapper<ImUser> imUserLambdaQueryWrapper = new LambdaQueryWrapper<>();
            imUserLambdaQueryWrapper.eq(ImUser::getUserId, groupUserId);
            ImUser imUser = imUserMapper.selectOne(imUserLambdaQueryWrapper);
            if (imUser.getId().equals(imUserGroup.getOwnerId())){
                ExceptionCast.cast(ErrorCode.GROUP_OWNER_NO_DELETE);
            }
        }
        Boolean aBoolean = tencentCloudImUtil.deleteGroupUser(imUserGroup.getGroupId(), deleteDto.getGroupUserIds());
        if (!aBoolean){
            ExceptionCast.cast(ErrorCode.DELETE_GROUP_USER_FAIL);
        }
    }
}
